<template>
  <div class="navbar">
    <div class="left-side">
      <div class="left-title">
        <div
          class="left-title-text"
          :style="menuPattern === 1 ? { cursor: 'pointer' } : {}"
          @click="toRootMenu"
        >
          <LogoIcon width="32" height="32" style="margin-right: 6px" />
          航空工业供应链管理系统
        </div>
        <SecretIcon class="left-title-mark" />
      </div>

      <!-- 折叠展开按钮，只对窄屏下的悬浮菜单生效 -->
      <icon-menu-fold
        v-if="!topMenu && appStore.device === 'mobile'"
        style="font-size: 22px; cursor: pointer"
        @click="toggleDrawerMenu"
      />
    </div>
    <div class="center-side">
      <Menu v-if="topMenu" />
    </div>
    <ul class="right-side">
      <!-- <li>
        <a-tooltip :content="$t('settings.search')">
          <a-button class="nav-btn" type="outline" :shape="'circle'">
            <template #icon>
              <icon-search />
            </template>
          </a-button>
        </a-tooltip>
      </li> -->
      <!-- <li>
        <a-tooltip :content="$t('settings.language')">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setDropDownVisible"
          >
            <template #icon>
              <icon-language />
            </template>
          </a-button>
        </a-tooltip>
        <a-dropdown trigger="click" @select="changeLocale as any">
          <div ref="triggerBtn" class="trigger-btn"></div>
          <template #content>
            <a-doption
              v-for="item in locales"
              :key="item.value"
              :value="item.value"
            >
              <template #icon>
                <icon-check v-show="item.value === currentLocale" />
              </template>
              {{ item.label }}
            </a-doption>
          </template>
        </a-dropdown>
      </li> -->
      <!-- <li>
        <a-tooltip
          :content="
            theme === 'light'
              ? $t('settings.navbar.theme.toDark')
              : $t('settings.navbar.theme.toLight')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="handleToggleTheme"
          >
            <template #icon>
              <icon-moon-fill v-if="theme === 'dark'" />
              <icon-sun-fill v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li> -->

      <!--消息通知-->
      <li>
        <a-tooltip :content="$t('settings.navbar.alerts')">
          <div class="message-box-trigger">
            <a-badge :count="9" dot>
              <icon-notification
                style="font-size: 20px; color: #e6e6e6"
                @click="setPopoverVisible"
              />
              <!-- <a-button
                class="nav-btn"
                type="outline"
                :shape="'circle'"
                @click="setPopoverVisible"
              >
              </a-button> -->
            </a-badge>
          </div>
        </a-tooltip>
        <a-popover
          trigger="click"
          :arrow-style="{ display: 'none' }"
          :content-style="{ padding: 0, minWidth: '400px' }"
          content-class="message-popover"
        >
          <div ref="refBtn" class="ref-btn"></div>
          <template #content>
            <message-box />
          </template>
        </a-popover>
      </li>
      <!-- <li>
        <a-tooltip
          :content="
            isFullscreen
              ? $t('settings.navbar.screen.toExit')
              : $t('settings.navbar.screen.toFull')
          "
        >
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="toggleFullScreen"
          >
            <template #icon>
              <icon-fullscreen-exit v-if="isFullscreen" />
              <icon-fullscreen v-else />
            </template>
          </a-button>
        </a-tooltip>
      </li> -->
      <!-- <li>
        <a-tooltip :content="$t('settings.title')">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setVisible"
          >
            <template #icon>
              <icon-settings />
            </template>
          </a-button>
        </a-tooltip>
      </li> -->
      <!--用户信息-->
      <li>
        <img
          src="@/common/components/image/userHeadImg.png"
          alt=""
          style="width: 24px"
        />
        <a-dropdown trigger="click">
          <!-- <a-avatar
            v-if="avatar"
            :size="32"
            :style="{ marginRight: '8px', cursor: 'pointer' }"
          >
            <img alt="avatar" :src="avatar" />
          </a-avatar>
          <a-avatar
            v-else
            :size="32"
            :style="{
              backgroundColor: '#7BC616',
              cursor: 'pointer',
              marginRight: '8px',
            }"
          >
            {{ username[0] }}
          </a-avatar> -->
          <div style="color: #fff; cursor: pointer">
            {{ username }}
            {{ currentOrgDeptInfo }}
            <icon-caret-down />
          </div>
          <template #content>
            <!-- <a-doption>
              <a-space @click="switchRoles">
                <icon-tag />
                <span>
                  {{ $t('messageBox.switchRoles') }}
                </span>
              </a-space>
            </a-doption> -->
            <!-- <a-doption>
              <a-space @click="$router.push({ name: 'Info' })">
                <icon-user />
                <span>
                  {{ $t('messageBox.userCenter') }}
                </span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="$router.push({ name: 'Setting' })">
                <icon-settings />
                <span>
                  {{ $t('messageBox.userSettings') }}
                </span>
              </a-space>
            </a-doption> -->

            <!--修改密码-->
            <a-doption>
              <a-space v-if="passwordEditable" @click="changePasswd">
                <icon-edit />
                <span>修改密码</span>
              </a-space>
            </a-doption>
            <a-doption v-if="canChangeOrg">
              <a-space @click="changeOrg">
                <icon-home />
                <span>组织机构设置</span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export />
                <span>
                  {{ $t('messageBox.logout') }}
                </span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>

    <PasswordModal v-model:visible="passwordModal" />
    <ChangeOrgModal v-model:visible="changeOrgModal" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, inject } from 'vue';
  // import { Message } from '@arco-design/web-vue';
  // import { useDark, useToggle, useFullscreen } from '@vueuse/core';
  import { useAppStore, useUserStore, useTabBarStore } from '@/store';
  // import { LOCALE_OPTIONS } from '@/locale';
  // import useLocale from '@/common/hooks/locale';
  import useUser from '@/common/hooks/user';
  import Menu from '@/common/components/menu/index.vue';
  import { useRouter } from 'vue-router';
  import { SecretLevel } from '@/common/constants';
  import LogoIcon from '@/assets/logo-avic.svg?component';
  import SecretIcon from '@/common/components/secret-icon/index.vue';
  import ChangeOrgModal from '@/common/components/navbar/change-org-modal.vue';
  import MessageBox from '../message-box/index.vue';
  import PasswordModal from './password-modal.vue';

  const appStore = useAppStore();
  const userStore = useUserStore();
  const tabBarStore = useTabBarStore();
  const { logout } = useUser();
  const changeOrgModal = ref<boolean>(false);
  // const { changeLocale, currentLocale } = useLocale();
  // const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();
  // const locales = [...LOCALE_OPTIONS];
  // const avatar = computed(() => {
  //   return userStore.avatar;
  // });

  // 用户名，取第一个字作为头像
  const username = computed(() => {
    return userStore.username || 'A';
  });
  // 用户当前的组织机构/部门信息
  const currentOrgDeptInfo = computed(() => {
    let orgDeptInfo = '';
    if (
      userStore.currentOrgId !== null &&
      userStore.currentOrgId !== undefined
    ) {
      const org = userStore.orgInfoList?.filter(
        (o) => o.id === userStore.currentOrgId
      ) as any[];
      if (org.length > 0) {
        const dept = org[0].deptInfoList.filter(
          (d: any) => d.id === userStore.currentDeptId
        );
        if (dept.length > 0) {
          orgDeptInfo = `${org[0].orgName} ${dept[0].deptName}`;
        }
      }
    }
    return orgDeptInfo;
  });
  const canChangeOrg = computed(() => {
    if (
      userStore.currentOrgId === null ||
      userStore.currentOrgId === undefined
    ) {
      return false;
    }
    return true;
  });
  const changeOrg = () => {
    changeOrgModal.value = true;
  };
  // 用户角色
  const roles = computed(() => userStore.roles || []);

  // const theme = computed(() => {
  //   return appStore.theme;
  // });
  // 系统密级
  const secretLevel = computed(() => appStore.secretLevel);
  const topMenu = computed(() => appStore.topMenu && appStore.menu);
  // const isDark = useDark({
  //   selector: 'body',
  //   attribute: 'arco-theme',
  //   valueDark: 'dark',
  //   valueLight: 'light',
  //   storageKey: 'arco-theme',
  //   onChanged(dark: boolean) {
  //     // overridden default behavior
  //     appStore.toggleTheme(dark);
  //   },
  // });
  // const toggleTheme = useToggle(isDark);
  // const handleToggleTheme = () => {
  //   toggleTheme();
  // };
  // const setVisible = () => {
  //   appStore.updateSettings({ globalSettings: true });
  // };
  const refBtn = ref();
  // const triggerBtn = ref();
  const setPopoverVisible = () => {
    const event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true,
    });
    refBtn.value.dispatchEvent(event);
  };
  const handleLogout = () => {
    logout();
  };

  const ADMINS = ['sysadmin', 'auditadmin', 'safeadmin'];
  const passwordEditable = computed(() => {
    // 机密级应用：仅三员可修改密码
    // 秘密及以下：所有人可修改密码
    if (secretLevel.value < SecretLevel['机密']) {
      return true;
    }
    return roles.value.find((role) => ADMINS.includes(role));
  });
  const passwordModal = ref<boolean>(false);
  const changePasswd = () => {
    passwordModal.value = true;
  };
  // const setDropDownVisible = () => {
  //   const event = new MouseEvent('click', {
  //     view: window,
  //     bubbles: true,
  //     cancelable: true,
  //   });
  //   triggerBtn.value.dispatchEvent(event);
  // };
  // const switchRoles = async () => {
  //   const res = await userStore.switchRoles();
  //   Message.success(res as string);
  // };
  const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;

  const menuPattern = computed(() => appStore.menuPattern);
  const router = useRouter();
  const toRootMenu = () => {
    if (menuPattern.value === 1) {
      tabBarStore.resetTabList();
      router.push({ name: 'rootMenu' });
    }
  };
</script>

<style scoped lang="less">
  :deep(.arco-badge) {
    color: white;
    cursor: pointer;
  }
  .navbar {
    display: flex;
    justify-content: space-between;
    height: 100%;
    // background-color: var(--color-bg-2);
    background: var(--color-blue-avic);
    border-bottom: 1px solid var(--color-border);
  }

  .left-side {
    display: flex;
    align-items: center;
    padding-left: 20px;

    .left-title {
      display: inline-flex;
      height: 32px;
      color: #fff;
      font-weight: bold;
      font-size: 22px;

      &-text {
        display: inline-flex;
        align-items: center;
      }

      &-mark {
        margin: 4px 0 0 6px;
        line-height: 18px;
      }
    }
  }

  .center-side {
    flex: 1;
  }

  .right-side {
    display: flex;
    padding-right: 20px;
    list-style: none;

    :deep(.locale-select) {
      border-radius: 20px;
    }

    li {
      display: flex;
      align-items: center;
      padding: 0 10px;
      img {
        margin-right: 14px;
      }
    }

    a {
      color: var(--color-text-1);
      text-decoration: none;
    }
    .nav-btn {
      color: rgb(var(--gray-8));
      font-size: 16px;
      border-color: rgb(var(--gray-2));
    }

    .trigger-btn,
    .ref-btn {
      position: absolute;
      bottom: 14px;
    }

    .trigger-btn {
      margin-left: 14px;
    }
  }
</style>

<style lang="less">
  .message-popover {
    .arco-popover-content {
      margin-top: 0;
    }
  }
</style>
